/*
 * @Description:
 * @Author: Zzt
 * @Date: 2022-12-21 11:34:26
 * @LastEditTime: 2023-01-29 10:39:09
 */
import { createContext, useReducer, useEffect, useContext } from 'react';
import {
  SET_SELECT_UNIT,
  SET_SELECTED_ITEM,
  GET_BUSINESS,
  DELETE_BUSINESS_ITEM,
  EDIT_BUSINESS,
  GET_ENCLOSURE,
  SAVE_ANNEX,
  DELECT_ANNUAL,
  ADD_ANNUAL,
  CLEAR_ANNUAL,
  SET_SEND_STATUS
} from '../constants';
import { BusinessGuidanceReducer } from '../reducers/BusinessGuidanceReducer';
import {
  readGuidanceById,
  searchGuidanceByPage,
  findGuidanceById
} from '@/api/onlineAndVirtual/guidanceAndFeedback';
import { message, Modal } from 'antd';
import {
  addAnnual,
  findAnnualById,
  searchAnnualByPage,
  deleteAnnualList,
  editAnnual
} from '@/api/onlineAndVirtual/annualInspection';

const initialState = {
  selectUnit: 0,
  // 选中的表格条目
  selectItems: [],
  businessList: [],
  sendStatusList: [
    { id: 1, name: '未读' },
    { id: 2, name: '已读' }
  ],
  readStatusList: [
    { id: 1, name: '未提交' },
    { id: 2, name: '待审核' },
    { id: 3, name: '审核中' },
    { id: 4, name: '审核通过' },
    { id: 5, name: '审核不通过' }
  ],
  enclosure: {},
  enclosureList: [],
  sendStatus: {}
};
const BusinessGuidanceContext = createContext();
const BusinessGuidanceContextProvider = (props) => {
  const [state, dispatch] = useReducer(BusinessGuidanceReducer, initialState);
  const actions = {
    /**
     * @description: 设置选中的单位
     * @param {object} data 选中的单位对象
     */
    setSelectUnit(data) {
      dispatch({ type: SET_SELECT_UNIT, data });
    },
    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },
    addAnnualList(params, type) {
      return new Promise((resolve, reject) => {
        addAnnual(params)
          .then((res) => {
            message.success('创建成功');
            const { data } = res;
            dispatch({ type: ADD_ANNUAL, data });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    /* 设置已读未读 */
    setSendStatus(data) {
      dispatch({ type: SET_SEND_STATUS, data });
    },
    /**
     * @description:
     * @param {*} params
     * @return {*}
     */
    getBusinessList(params, type) {
      return new Promise((resolve, reject) => {
        type === 3
          ? searchAnnualByPage(params)
              .then((res) => {
                const { data } = res;
                dispatch({ type: GET_BUSINESS, data: data.results });
                resolve(data);
              })
              .catch((err) => {
                reject(err);
              })
          : searchGuidanceByPage(params)
              .then((res) => {
                const { data } = res;
                dispatch({ type: GET_BUSINESS, data: data.results });
                resolve(data);
              })
              .catch((err) => {
                reject(err);
              });
      });
    },

    /* 删除选中列表 */
    deleteItem(id, title = '是否移除选中的年检审核?') {
      Modal.confirm({
        title,
        content: '是否删除此年检？，删除后不可恢复。',
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteAnnualList(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            message.success('移除成功');
            dispatch({ type: DELETE_BUSINESS_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('del item Cancel');
        }
      });
    },
    /* 读后修改列表 */
    readGuidance(id) {
      return new Promise((resolve, reject) => {
        readGuidanceById(id)
          .then((res) => {
            const { data } = res;
            const { id } = res.data;
            dispatch({ type: EDIT_BUSINESS, id, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },
    /* 修改任务 */
    editBusinessList(params) {
      return new Promise((resolve, reject) => {
        editAnnual(params)
          .then((res) => {
            const { data } = res;
            const { id } = res.data;
            dispatch({ type: EDIT_BUSINESS, id, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },
    /* 获取指导意见中附件 */
    getEnclosure(id, type) {
      return new Promise((resolve, reject) => {
        type === 3
          ? findAnnualById(id)
              .then((res) => {
                const { data } = res;
                dispatch({ type: GET_ENCLOSURE, data });
                resolve(data);
              })
              .catch((err) => {
                reject(err);
              })
          : findGuidanceById(id)
              .then((res) => {
                const { data } = res;
                dispatch({ type: GET_ENCLOSURE, data });
                resolve(data);
              })
              .catch((err) => {
                reject(err);
              });
      });
    },
    /* 表格显示附件 */
    SaveAnnex(data) {
      dispatch({ type: SAVE_ANNEX, data });
    },
    /* 删除一项附件 */
    DeleteAnnual(id) {
      dispatch({ type: DELECT_ANNUAL, id });
    },
    /* 清空缓存附件 */
    ClearAnnex() {
      dispatch({ type: CLEAR_ANNUAL });
    }
  };
  const filters = {
    resultFilter(id) {
      return state.sendStatusList.find((item) => item.id === id)?.name || '-';
    },
    readFilter(id) {
      return state.readStatusList.find((item) => item.id === id)?.name || '-';
    }
  };
  useEffect(() => {}, []);
  return (
    <BusinessGuidanceContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </BusinessGuidanceContext.Provider>
  );
};
export const useBusinessGuidanceContext = () => {
  return useContext(BusinessGuidanceContext);
};
export { BusinessGuidanceContext, BusinessGuidanceContextProvider };
